package com.xcity.config;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;

import naga.x.App;
import naga.x.common.Config;
import naga.x.net.impl.pomelo.PomeloMessage;
import naga.x.net.impl.pomelo.config.Dictionary;
import naga.x.net.impl.pomelo.protocol.Message;
import naga.x.util.ClassUtil;
import naga.x.util.KeywordsManager;
import naga.x.util.StringUtils;

public class ConfigLoader {
	
	public static <T extends Config> T init(String name, Class<T> configClass) throws Exception {
		T config = JSON.parseObject(Thread.currentThread().getContextClassLoader().getResourceAsStream(name), configClass);
		String pkgDict = config.dict;//config.getString(Config.POMELO_DICT);
		if (StringUtils.isNotEmpty(pkgDict)) {
//			List<Class<?>> classes = ClassUtils.scanPackage(pkgDict, true);
			Set<Class<?>> classes = ClassUtil.scanPackage(pkgDict);
			short routeCode = 0;
			Map<String, Short> dict = new LinkedHashMap<String, Short>();
			Map<Short, Class<?>> classesOfRequest = new LinkedHashMap<Short, Class<?>>();
			for (Class<?> clazz : classes) {
				PomeloMessage pm = clazz.getDeclaredAnnotation(PomeloMessage.class);
				Deprecated dep = clazz.getDeclaredAnnotation(Deprecated.class);
				if (pm != null && pm.type() == Message.Type.REQUEST && dep == null) {
					dict.put(pm.route(), ++routeCode);
					classesOfRequest.put(routeCode, clazz);
				}
			}
//			config.put(Config.POMELO_DICT, new Dictionary(dict, classesOfRequest));
			config.dictionary = new Dictionary(dict, classesOfRequest);
		}
		
		App.getApp().setConfig(config);
		return config;
	}

	public static void init(String name) throws Exception {
		ConfigEx config = init(name, ConfigEx.class);
		File file = new File(config.badwordsFile);
		if (file.exists()) {
			config.badwordsFilter = new KeywordsManager(file, null);
		}
	}
	
	
	
}
